package com.xiaoxx.rabbitmq.db.typehandler;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;

import com.xiaoxx.rabbitmq.bean.MyMessage;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;



@MappedTypes(MyMessage.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MessageJsonTypeHandler extends BaseTypeHandler<MyMessage<Object>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, MyMessage parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSONObject.toJSONString(parameter));
    }

    @Override
    public MyMessage<Object> getNullableResult(ResultSet rs, String columnName)throws SQLException {
    	String value = rs.getString(columnName);
    	if(!StringUtils.hasText(value)) {
    		return JSONObject.parseObject(value,MyMessage.class);
    	}
    	return null;  
    }

    @Override
    public MyMessage<Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    	String value = rs.getString(columnIndex);
    	if(!StringUtils.hasText(value)) {
    		return JSONObject.parseObject(rs.getString(columnIndex),MyMessage.class);
    	}
    	return null;         
    }

    @Override
    public MyMessage<Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    	String value = cs.getString(columnIndex);
    	if(!StringUtils.hasText(value)) {
    		return JSONObject.parseObject(cs.getString(columnIndex), MyMessage.class);
    	}
    	return null;   
    }

}